using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Grafica2
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Effect fx;
        Model model;


        CameraManager camera;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            camera = new CameraManager(this);
            Components.Add(camera);

        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {

            base.Initialize();
            RasterizerState rast = new RasterizerState();
            rast.CullMode = CullMode.None;
//            rast.FillMode = FillMode.WireFrame;
            rast.FillMode = FillMode.Solid;
            GraphicsDevice.RasterizerState = rast;
            camera.CurrentCamera.AspectRatio = GraphicsDevice.Viewport.AspectRatio;
            camera.CurrentCamera.View = Matrix.CreateLookAt(Vector3.Backward * 50 + Vector3.Up * 30, Vector3.Up * 30, Vector3.Up);
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            model = Content.Load<Model>("polok");
            var fx = Content.Load<Effect>("Phong");

            foreach (var m in model.Meshes)
            {
                foreach (var mp in m.MeshParts)
                {
                    var bf = (BasicEffect)mp.Effect;
                    bf.EnableDefaultLighting();
                    var myfx = fx.Clone();
                    myfx.Parameters["SpecularPower"].SetValue(bf.SpecularPower);
                    myfx.Parameters["SpecularColor"].SetValue(Color.White.ToVector4());
                    myfx.Parameters["DiffuseColor"].SetValue(new Vector4(bf.DiffuseColor, 255));
                    myfx.Parameters["AmbientLightColor"].SetValue(new Vector4(bf.AmbientLightColor, 255));

                    myfx.Parameters["Direction0"].SetValue(bf.DirectionalLight0.Direction);
                    myfx.Parameters["DiffuseColor0"].SetValue(new Vector4(bf.DirectionalLight0.DiffuseColor, 255));
                    myfx.Parameters["SpecularColor0"].SetValue(new Vector4(bf.DirectionalLight0.SpecularColor, 255));

                    myfx.Parameters["Direction1"].SetValue(bf.DirectionalLight1.Direction);
                    myfx.Parameters["DiffuseColor1"].SetValue(new Vector4(bf.DirectionalLight1.DiffuseColor, 255));
                    myfx.Parameters["SpecularColor1"].SetValue(new Vector4(bf.DirectionalLight1.SpecularColor, 255));

                    myfx.Parameters["Direction2"].SetValue(bf.DirectionalLight2.Direction);
                    myfx.Parameters["DiffuseColor2"].SetValue(new Vector4(bf.DirectionalLight2.DiffuseColor, 255));
                    myfx.Parameters["SpecularColor2"].SetValue(new Vector4(bf.DirectionalLight2.SpecularColor, 255));

                    


                    mp.Effect = myfx;
                }               

            }

           // GraphicsDevice.RasterizerState = RasterizerState.CullNone;
            IsMouseVisible = true;

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            foreach (var mesh in model.Meshes)
            {
                foreach (var fx in mesh.Effects)
                {
                    fx.Parameters["World"].SetValue(Matrix.Identity);
                    fx.Parameters["View"].SetValue(camera.CurrentCamera.View);
                    fx.Parameters["Projection"].SetValue(camera.CurrentCamera.Projection);
                    fx.Parameters["LightPosition"].SetValue(new Vector4(200, 200, 200, 1));
                    fx.Parameters["EyePosition"].SetValue(camera.CurrentCamera.position);
                    fx.CurrentTechnique = fx.Techniques["PerPixelPhongShading"];
                    //fx.CurrentTechnique = fx.Techniques["GouraudShading"];
                    //fx.CurrentTechnique = fx.Techniques["FlatShading"];
                }

                mesh.Draw();

                //foreach (var mp in mesh.MeshParts)
                //{
                //    GraphicsDevice.SetVertexBuffer(mp.VertexBuffer);
                //    GraphicsDevice.Indices = mp.IndexBuffer;
                //    //mp.Effect.Techniques["FlatShading"].Passes[0].Apply();
                //    mp.Effect.CurrentTechnique = mp.Effect.Techniques["PerPixelPhongShading"];
                //    mp.Effect.CurrentTechnique.Passes[0].Apply();
                //    GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, mp.NumVertices, mp.StartIndex, mp.PrimitiveCount);
                //}

               

            }

            base.Draw(gameTime);
        }
    }
}
